<template>
    <Dialog :app-dialog="appDialog" @close="close">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="110px" class="upload-voice">
            <!-- 分组 -->
            <el-form-item label="分组">
                <el-cascader
                    ref="cascaderRef"
                    v-model="form.group"
                    style="width: 100%"
                    :options="groupData"
                    :props="defaultProps"
                    placeholder="请选择分组"
                    @change="orgChange" />
            </el-form-item>
            <!-- 类型 -->
            <el-form-item label="类型" class="form-radio">
                <el-radio-group v-model="form.type" class="radio_list" @change="changeType">
                    <el-radio v-for="item in typeDiff" :key="item.value" :label="item.value" class="radio_list_item">
                        <span class="radio_list_item_text">{{ item.name }}</span>
                        <el-tooltip v-if="item.value === 1" :content="item.text" placement="bottom">
                            <div class="radio_list_item_icon radio_img">
                                <img src="@/assets/image/material/question.png" alt="" />
                            </div>
                        </el-tooltip>
                    </el-radio>
                </el-radio-group>
            </el-form-item>
            <!-- 上传文件 -->
            <ZWUpload ref="emptyData" :up-info="voiceInfo" @submit="getFileList" />
            <el-form-item>
                <template #label>
                    <div class="label_text">
                        <span>素材标签</span>
                        <el-tooltip :content="tagTips.materialTagTips" placement="top">
                            <img src="@/assets/image/material/question.png" alt="" />
                        </el-tooltip>
                    </div>
                </template>
                <selectTags ref="tagIdsRef" v-model="form.tag_ids" />
            </el-form-item>
            <el-form-item v-if="form.type == 1" label="是否强制授权">
                <el-radio-group v-model="form.is_force_grant" @change="changeAuth">
                    <el-radio :label="1">否</el-radio>
                    <el-radio :label="2">是</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item v-show="form.is_force_grant == 2 && form.type == 1" label="授权内容">
                <el-checkbox-group v-model="form.grant_params">
                    <el-checkbox label="offical_headimg_nickname">头像昵称（公众号）</el-checkbox>
                    <el-checkbox label="phone">手机号（小程序）</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item v-if="form.type == 1">
                <template #label>
                    <div class="label_text">
                        <span>浏览打标</span>
                        <el-tooltip :content="tagTips.browseCustTips" placement="top">
                            <img src="@/assets/image/material/question.png" alt="" />
                        </el-tooltip>
                    </div>
                </template>
                <selectTags ref="viewtagIdsRef" v-model="form.view_tag_ids" :type="2" />
            </el-form-item>
            <el-form-item v-if="form.type == 1">
                <template #label>
                    <div class="label_text">
                        <span>分享打标</span>
                        <el-tooltip :content="tagTips.shareCustTips" placement="top">
                            <img src="@/assets/image/material/question.png" alt="" />
                        </el-tooltip>
                    </div>
                </template>
                <selectTags ref="shareTagIdsRef" v-model="form.share_tag_ids" :type="2" />
            </el-form-item>

            <el-form-item label="">
                <div class="agree_ment">
                    <!-- 暂时隐藏掉,协议要先不上需要法务确认 -->
                    <!-- <el-checkbox v-model="form.check" @change="confirmSure"></el-checkbox>
          <span class="ml2">勾选代表同意</span>
          <el-link class="form-link" type="primary" :underline="false">《***用户协议》</el-link> -->
                </div>
            </el-form-item>
        </el-form>
    </Dialog>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch, onUnmounted, toRefs } from 'vue';
import Dialog from '@/components/Dialog.vue';
import ZWUpload from './ZWUpload.vue';
import selectTags from '../../../components/selectTags.vue';
import { uplodVoice, getVoiceInfo, changeVoice, getGroupList } from '@/api/concreation';
import { ElForm, ElMessage } from 'element-plus';
import { getSetionId, IsNotEmpty } from '@/utils/utils';
import bus from '@/utils/bus';
import { endLoading } from '@/utils/request';
const formRef = ref<InstanceType<typeof ElForm>>();
const emit = defineEmits(['submit']);
const props = defineProps(['groupId', 'type']);
import { useStore } from '@/store';
const store = useStore();
const cascaderRef: any = ref(null); // 选择分组ref
const uploadTitle = ref('上传文件');
const uploadVisib = ref(false);
const imageId = reactive({
    media_content_id: ''
}); // 编辑图片 id
const isEdit = ref(false);
const emptyData = ref(); // 清空回显数据
const tagType = ref(1);
const tagIdsRef = ref(null);
const viewtagIdsRef = ref(null);
const shareTagIdsRef = ref(null);
const tagTips = {
    materialTagTips: '该素材会被打上此素材标签，在列表上会展示',
    browseCustTips: '浏览该素材的客户将被打上此客户标签',
    shareCustTips: '点击该素材的分享按钮并生成分享链接的客户将被打上此客户标签'
};
// 1-文本 2-图片 3-音频 4-视频 5-文件 6-链接文章 7-链接引用
// eslint-disable-next-line vue/no-dupe-keys
const { type, groupId } = toRefs(props);
//上传弹框
const uploadInfo = computed(() => {
    return store.getters['content/upload'];
});
// 分组列表
const groupData = ref([]);

/**
 * @description: 获取分组数据
 * @return {*}
 */
const getGroupListFunc = async () => {
    const res = await getGroupList({ type: props.type });
    groupData.value = res.data;
};
//标签
const tags = ref([]);
const defaultProps = {
    checkStrictly: true,
    emitPath: false,
    label: 'name',
    value: 'id'
};
const form = reactive({
    tag_ids: [],
    view_tag_ids: [],
    is_force_grant: 1,
    group: '', //分组
    type: 1, //0普通音频1雷达音频
    voice: '', // 音频文件
    check: true, //用户协议
    title: '', //标题
    id: '', //内容id
    share_tag_ids: [],
    grant_params: ['offical_headimg_nickname', 'phone']
});

const rules = reactive({
    voice: { required: true, message: '语音不能为空', trigger: ['change', 'blur'] },
    title: { required: true, message: '标题不能为空', trigger: 'blur' }
});

const close = () => {
    form.group = groupId.value;
    tags.value.splice(0);
    form.type = 1;
    formRef.value.resetFields();
};

const changeType = (val: any) => {
    if (val == 0) {
        form.is_force_grant = '';
    } else if (val == 1) {
        form.is_force_grant = 1;
    }
};

// 语音上传
const voiceInfo = reactive({
    type: 4,
    label: '语音',
    prop: 'voice',
    files: form.voice,
    multiple: false,
    limitSize: 2,
    acceptFile: '.mp3,.wav,.m4a,.MP3,.WAV,.M4A'
});
const typeDiff = reactive([
    { value: 0, name: `普通音频` },
    {
        value: 1,
        name: `雷达音频`,
        text: `雷达音频可以追踪客户端浏览次数、时间等数据`
    }
]);
// 获取上传成功的文件
const getFileList = (data: any) => {
    try {
        if (!IsNotEmpty(data)) {
            form.voice = '';
            return;
        }
        form.voice = getSetionId('code', data)[0];
    } catch (error) {
    } finally {
        endLoading();
    }
};
const changeAuth = () => {
    if (form.is_force_grant == 1) {
        form.grant_params = [];
    } else {
        form.grant_params = ['offical_headimg_nickname', 'phone'];
    }
};
// 取消
const cancelHandel = () => {
    appDialog.visible = false;
    isEdit.value = false;
    delUpform();
    close();
    formRef.value.resetFields();
};
//确定
const submitHandel = () => {
    formRef.value.validate(async (valid: any) => {
        if (valid) {
            const grant = {
                offical_headimg_nickname: form.grant_params.includes('offical_headimg_nickname') ? 2 : 1,
                phone: form.grant_params.includes('phone') ? 2 : 1
            };
            const params = {
                title: form.title,
                group_id: form.group,
                file_type: form.type,
                code: form.voice,
                tag_ids: getSetionId('id', form.tag_ids),
                view_tag_ids: getSetionId('id', form.view_tag_ids),
                is_force_grant: form.is_force_grant,
                grant_params: grant,
                share_tag_ids: getSetionId('id', form.share_tag_ids)
            };
            if (form.type === 0) {
                delete params.view_tag_ids;
                delete params.share_tag_ids;
            }
            if (isEdit.value) params.media_content_id = form.id;
            const res = isEdit.value ? await changeVoice(params) : await uplodVoice(params);
            ElMessage.success(`${isEdit.value ? '修改' : '上传'}音频成功`);
            cancelHandel();
            close();
            emit('submit', { id: params.group_id });
        }
    });
};
const appDialog = reactive({
    visible: uploadVisib,
    title: uploadTitle,
    width: '670px',
    cancel: cancelHandel,
    submit: submitHandel,
    isDisable: false,
    cancelText: '取消',
    submitText: '保存'
});
const confirmSure = (val: boolean) => {
    appDialog.isDisable = !val;
};
//获取编辑内容
const editItem = (data: any) => {
    isEdit.value = true;
    if (type.value == 3) {
        imageId.media_content_id = data.id;
        getVoiceInfo(imageId).then((data: any) => {
            // tag_ids 素材标签
            // view_tag_ids 浏览客户标签
            // share_tag_ids 分享客户标签
            form.tag_ids = data.tag_info;
            form.view_tag_ids = data.view_tag_info;
            form.share_tag_ids = data.share_tag_info;
            form.title = data.title;
            form.group = data.group_id;
            form.type = data.is_radar;
            form.voice = data.media_content_media.media_file.code;
            form.id = data.id;
            form.is_force_grant = data.is_force_grant;
            form.grant_params = [];
            if (data.grant_params?.offical_headimg_nickname == 2) {
                form.grant_params.push('offical_headimg_nickname');
            }
            if (data.grant_params?.phone == 2) {
                form.grant_params.push('phone');
            }
            emptyData.value.echo(data.media_content_media);
            setTimeout(() => {
                tagIdsRef.value?.init();
                viewtagIdsRef.value?.init();
                shareTagIdsRef.value?.init();
            }, 0);
        });
    }
};
// 清空上传表单数据
const delUpform = () => {
    Object.keys(form).map(key => {
        if (key !== 'group' && key !== 'type' && key !== 'check') {
            if (key === 'tags') {
                form[key] = [];
            } else {
                delete form[key];
            }
        }
    });
    emptyData.value.empty();
};
bus.on('delUpform', delUpform);
bus.on('editItem', editItem);
watch(uploadInfo, uploadInfo => {
    uploadTitle.value = uploadInfo.title;
    uploadVisib.value = uploadInfo.uploadVisib;
    if (uploadVisib.value) {
        getGroupListFunc();
    }
    form.grant_params = ['offical_headimg_nickname', 'phone'];
    form.is_force_grant = 1;
});
watch(
    () => groupId.value,
    val => (form.group = val),
    { immediate: true }
);
watch(
    () => form.voice,
    val => formRef.value.validateField('voice')
);

// 选择完地区后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};
onUnmounted(() => {
    bus.off('editItem', editItem);
});
</script>

<style lang="scss" scoped>
.upload-voice {
    padding-top: 14px;

    .form-radio {
        line-height: normal;

        :deep(.el-form-item__label),
        :deep(.el-form-item__content) {
            line-height: normal;
        }

        .el-radio {
            height: auto;
        }
    }
}

.radio_list {
    &_item {
        &_icon {
            width: 14px;
            height: 14px;
            margin: -3px 0 0 6px;

            img {
                margin-top: 2px;
                width: 100%;
                height: 100%;
                vertical-align: top;
            }
        }
    }

    :deep .el-radio__label {
        display: flex;
        align-items: center;
    }
}

.ml2 {
    margin-left: 2px;
}

.mr10 {
    margin-right: 10px;
}

.agree_ment {
    display: flex;
    align-items: center;
}

:deep .el-scrollbar {
    height: 50%;
}

:deep(.el-form-item) {
    .label_text {
        display: flex;
        align-items: center;
        gap: 6px;

        img {
            width: 14px;
            height: 14px;
        }
    }
}
</style>
